package top.vanchor.flexible.utils;

import top.vanchor.flexible.entity.model.DateRange;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 98523
 * @create 2024/4/13 17:59
 */
public class StringUtils {

    /**
     * int 转 固定位数的String
     *
     * @param val   值
     * @param width 位数（10位以内<不含>）
     * @return 字符串
     */
    public static String intToString(int val, int width) {
        return String.format("%0" + width + "d", val);
    }

    public static Date dateFormat(String pattern, String str) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 合并日期
     * @param dateRanges List<DateRange> ，如[(2023-07-01,2023-07-31),(2023-08-01,2023-08-31)]
     * @return List<String> ，如[202307-202308]
     */
    public static List<String> mergeDateRanges(List<DateRange> dateRanges) {
        List<String> mergedRanges = new ArrayList<>();
        String currentRangeStart = null;
        String currentRangeEnd = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        for (DateRange range : dateRanges) {
            String startYearMonth = sdf.format(range.getBeginTime());
            String endYearMonth = sdf.format(range.getEndTime());

            if (currentRangeStart == null) {
                currentRangeStart = startYearMonth;
                currentRangeEnd = endYearMonth;
            } else if (startYearMonth.equals(currentRangeEnd) ||
                    isNextMonth(currentRangeEnd, startYearMonth)) {
                currentRangeEnd = endYearMonth;
            } else {
                mergedRanges.add(currentRangeStart + "-" + currentRangeEnd);
                currentRangeStart = startYearMonth;
                currentRangeEnd = endYearMonth;
            }
        }

        // Add the last range
        if (currentRangeStart != null) {
            mergedRanges.add(currentRangeStart + "-" + currentRangeEnd);
        }

        return mergedRanges;
    }

    private static boolean isNextMonth(String current, String next) {
        int currentYear = Integer.parseInt(current.substring(0, 4));
        int currentMonth = Integer.parseInt(current.substring(4, 6));
        int nextYear = Integer.parseInt(next.substring(0, 4));
        int nextMonth = Integer.parseInt(next.substring(4, 6));

        return (currentYear == nextYear && currentMonth + 1 == nextMonth) ||
                (currentYear + 1 == nextYear && currentMonth == 12 && nextMonth == 1);
    }

}
